package com.hang.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hang.context.TenantContextHolder;
import com.hang.service.TenantDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TenantInterceptor implements HandlerInterceptor {
    @Autowired
    private TenantDataSourceService tenantDataSourceService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 从请求头获取租户编码
        String tenantCode = request.getHeader("X-Tenant-Code");
        if (StringUtils.isBlank(tenantCode)) {
            throw new RuntimeException("请求头缺失 X-Tenant-Code");
        }

        // 2. 验证租户并动态注册数据源
        tenantDataSourceService.loadAndRegisterDataSource(tenantCode);
        TenantContextHolder.setTenantCode(tenantCode);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 3. 清理租户上下文
        TenantContextHolder.clear();
    }
}
